package forum.dao.memory;

import forum.dao.UserDAO;
import forum.entities.User;
import forum.exceptions.CreateExistingEntityException;

import java.math.BigInteger;
import java.util.Iterator;

public class MemoryUserDAO extends MemoryGenericDAO<User> implements UserDAO {


    // TODO This is stupid full search.
    // Change it for more efficient algorithm (maybe change data store collection)
    @Override
    public User findUserByEmail(String email) {
        Iterator<User> it = getEntitiesIterator();
        User user = null;
        while(it.hasNext()) {
            User record = it.next();
            if (record.getEmail().equals(email)) {
                user = record;
            }
        }
        return user;
    }

    @Override
    public User findUserByNickname(String nickname) {
        Iterator<User> it = getEntitiesIterator();
        User user = null;
        while(it.hasNext()) {
            User record = it.next();
            if (record.getNickName().equals(nickname)) {
                user = record;
            }
        }
        return user;
    }

    @Override
    public User read(BigInteger id) {
        return super.read(id);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public void update(User entity) throws CreateExistingEntityException {
        if (findUserByEmail(entity.getEmail()) != null) {
            throw new CreateExistingEntityException("User with email "+ entity.getEmail() +" already exists");
        }
        if (findUserByNickname(entity.getNickName()) != null) {
            throw new CreateExistingEntityException("User with nickname"+ entity.getNickName() +" already exists");
        }
        super.update(entity);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public void delete(BigInteger id) {
        super.delete(id);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public User create() {
        return new User(super.create());    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    protected User newEntity() {
        return new User(getNewKey());
    }


}
